package com.lagouwork.zcx;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Client extends Frame {

    private TextField textFieldContent = new TextField();//输入框
    private final TextArea textAreaContent = new TextArea();//显示部分
    private Socket socket = null;
    private OutputStream out = null;//对于服务器来说，向客服端传出去数据
    private DataOutputStream dos = null;//用来创建数据输出流对象
    private InputStream in = null;//对客户端来说，从服务器上取入数据
    private DataInputStream dis = null;//用来创建数据输入流对象
    private boolean flag = false;//连接状态

    /**
     * 功能：启动客户端程序
     */
    public static void main(String[] args) {
        while(true) {
            Scanner input = new Scanner(System.in);//创建一个键盘扫描类对象
            System.out.println("\n" + "********************" + "操作提示: 创建用户[c / C]" + "********************");
            String contents1 = input.next(); //输入字符串型
            if (contents1.equals("c") || contents1.equals("C"))
            {
                System.out.println("请输入用户名：");
                String contents2 = input.next(); //输入字符串型
                new Client().init(contents2);
            }

        }
    }

    /**
     * 功能：对窗口进行初始化
     */
    private void init( String userName) {
        this.setSize(300, 300);
        setLocation(250, 150);
        setVisible(true);
        setTitle(userName);

        // 添加控件
        this.add(textAreaContent);
        this.add(textFieldContent, BorderLayout.SOUTH);
        textAreaContent.setFocusable(false);//setFocusable(boolean focusable) 表明此 Component 是否可以获得焦点。
        pack();//依据你放置的组件设定窗口的大小 使之正好能容纳你放置的所有组件

        // 关闭事件
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.out.println("用户试图关闭窗口");
                disconnect();
                System.exit(0);
            }

        });
        // textFieldContent添加回车事件
        textFieldContent.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onClickEnter();
            }
        });

        // 建立连接
        connect(userName);
        new Thread(new ReceiveMessage()).start();
    }

    /**
     * 功能：接收由服务端发来的消息
     */
    private class ReceiveMessage implements Runnable {
        @Override
        public void run() {
            flag = true;
            try {
                while (flag) {
                    String message = dis.readUTF();//收到的消息
                    textAreaContent.append("\n" + "接收消息" + "\t" + message + "\n");
                }
            } catch (EOFException e) {
                flag = false;
                System.out.println("客户端已关闭");
                // e.printStackTrace();
            } catch (SocketException e) {
                flag = false;
                System.out.println("客户端已关闭");
                // e.printStackTrace();
            } catch (IOException e) {
                flag = false;
                System.out.println("接受消息失败");
                e.printStackTrace();
            }
        }

    }

    /**
     * 功能：当点击回车时出发的事件
     */
    private void onClickEnter() {
        String message = textFieldContent.getText().trim();
        if (message != null && !message.equals("")) {
            String user = this.getTitle();
            String time = new SimpleDateFormat("h:m:s").format(new Date());
            textAreaContent.append("\n" + "发送消息" + "\t" + time + "\n"  + user + ":\t" + message + "\n");
            textFieldContent.setText("");
            sendMessageToServer(message,user,time);//向服务器发送消息
            System.out.println(time + "\t" + user +"\t" + "发送了消息:\t" + message);
        }
    }

    /**
     * 功能：给服务器发送消息
     *
     * @param message
     */
    private void sendMessageToServer(String message, String user, String time) {
        try {
            dos.writeUTF( time + "\n"  + user + ":\t" + message);
            dos.flush();
        } catch (IOException e) {
            System.out.println("发送消息失败");
            e.printStackTrace();
        }
    }

    /**
     * 功能：申请socket链接
     */
    private void connect(String userName) {
        try {
            socket = new Socket("localhost", 8888);
            out = socket.getOutputStream();//对于服务器来说，向客服端传出去数据
            dos = new DataOutputStream(out);
            in = socket.getInputStream();//对客户端来说，从服务器上取入数据
            dis = new DataInputStream(in);//用来创建数据输入流对象
        } catch (UnknownHostException e) {
            System.out.println("申请链接失败");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("申请链接失败");
            e.printStackTrace();
        }
    }

    /**
     * 功能：关闭流和链接
     */
    private void disconnect() {
        flag = false;
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                System.out.println("dos关闭失败");
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                System.out.println("dos关闭失败");
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("socket关闭失败");
                e.printStackTrace();
            }
            ;
        }
    }

}